//
//  BindLoginFlow.swift
//  casdon_swiftUI
//
//  Created by ww on 2025/5/18.
//
// 使用三方授权登录时弹出绑定账号， 绑定用户账号流程

import Combine

final class BindLoginFlow {
    // 第一步获取验证码
    // 校验验证码
    // 再次登陆
    
    private let cdRequestCodeStep:   CDGetVerifyCodeStep        // 第一步，调用凯度云获取验证码
    private var codeInpuStep: AnyPublisher<String, Never>?      // 第二步，用户输入验证码
    private let cdVerifyCodeStep: CDValidateCodeStep        // 第三步校验验证码
    private let cdWechatLoginStep:   CDWechatLoginStep      //         第四步，调用凯度云接口使用微信返回的token登录，若返回10012错误码，则进入绑定登录流程bindLoginFlow（viewmodel中操作）
    private let cdGetUserInfoStep: CDGetUserLoginInfoStep    // 第五步，调用凯度云服务获取用户信息
    private let tuyaLoginPwdStep: TuyaLoginPwdStep      // 第6步，调用涂鸦的账号密码登录

    init(codeInput: AnyPublisher<String, Never>)  {
        cdRequestCodeStep = CDGetVerifyCodeStep()
        codeInpuStep = codeInput
        cdVerifyCodeStep = CDValidateCodeStep()
        cdWechatLoginStep = CDWechatLoginStep()
        tuyaLoginPwdStep = TuyaLoginPwdStep()
        cdGetUserInfoStep = CDGetUserLoginInfoStep()
    }
    
    func start(account: String, code: String, state: String, source: String) -> AnyPublisher<Void, Error> {
        
        cdRequestCodeStep.execute(.init(account: account, type: RequestCodeType.notRegister))
            .flatMap { [weak self] _ -> AnyPublisher<String, Error> in
                guard let self = self, let codeInpuStep = self.codeInpuStep else {
                    return Fail(error: FlowError.stepMissing).eraseToAnyPublisher()
                }
                return codeInpuStep
                    .setFailureType(to: Error.self)
                    .eraseToAnyPublisher()
            }
            .flatMap { [weak self] authResult -> AnyPublisher<AuthAPI.WechatLogin.Response, Error> in
                return self?.cdWechatLoginStep.execute(.init(socialCode: code, socialState: state)) ?? Fail(error: FlowError.stepMissing).eraseToAnyPublisher()
            }
            .flatMap { [weak self] response -> AnyPublisher<AuthAPI.UserLogInInfo.Response, Error> in
                AuthManager.shared.saveToken(response.access_token)
                return self?.cdGetUserInfoStep.execute(.init()) ?? Fail(error: FlowError.stepMissing).eraseToAnyPublisher()
            }
            .flatMap { [weak self] userInfo -> AnyPublisher<Void, Error> in
                return self?.tuyaLoginPwdStep.execute(.init(account:  userInfo.userName, password: userInfo.password)) ?? Fail(error: FlowError.stepMissing).eraseToAnyPublisher()
            }
            .eraseToAnyPublisher()
    }
    
}
